import React, { FC, useState, ChangeEvent } from 'react'
import { useDispatch } from 'react-redux'
import { useRequest, useKeyPress, useDebounceEffect } from 'ahooks'
import { useNavigate, useParams } from 'react-router-dom'
import { Button, Typography, Space, Input, message } from 'antd'
import { LeftOutlined, EditOutlined, LoadingOutlined } from '@ant-design/icons'
import { updateQuestionServices } from '../../../../services/question'
import { changePageTitle } from '../../../../store/pageInfoReducer'
import useGetPageInfo from '../../../../hooks/useGetPageInfo'
import useGetComponentInfo from '../../../../hooks/useGetComponentInfo'
import EditToolbar from '../EditToolbar/EditToolbar'
import styles from './EditHeader.module.scss'
const { Title } = Typography

// 显示和修改页面标题
const TitleElem: FC = () => {
    const dispatch = useDispatch()
    const { title } = useGetPageInfo()
    const [editState, setEditState] = useState(false)

    // 修改编辑状态
    const handleEdit = () => {
        setEditState(true)
    }
    // 改变页面标题
    const handleChangeTitle = (event: ChangeEvent<HTMLInputElement>) => {
        const newTitle = event?.target.value.trim()
        if (!newTitle) return
        else dispatch(changePageTitle(newTitle))
    }
    if (editState) {
        return (
            <Input
                value={title}
                onPressEnter={() => setEditState(false)}
                onBlur={() => setEditState(false)}
                onChange={handleChangeTitle}
            />
        )
    }
    return (
        <Space>
            <Title>{title}</Title>
            <Button icon={<EditOutlined />} type="text" onClick={handleEdit} />
        </Space>
    )
}

/***
 * 保存按钮组件逻辑
 * 保存当前问卷的全部信息，即pageInfo + component
 */
const SaveEButtonElem: FC = () => {
    const { id } = useParams() // 问卷id
    const { componentsList = [] } = useGetComponentInfo() // 问卷组件列表
    const pageInfo = useGetPageInfo() // 问卷页面信息
    const { loading, run: handleSave } = useRequest(
        async () => {
            if (!id) return
            await updateQuestionServices(id, { ...pageInfo, componentsList })
        },
        {
            manual: true,
        }
    )
    // 快捷键保存
    useKeyPress(['ctrl.s', 'meta.s'], (event: KeyboardEvent) => {
        event.preventDefault() // 阻止默认行为
        if (!loading) handleSave()
    })
    // 自动保存(不是定时器保存，监听信息变化 + 防抖模式来保存)
    useDebounceEffect(
        () => {
            handleSave()
        },
        [pageInfo, componentsList],
        {
            wait: 1000,
        }
    )
    return (
        <Button onClick={handleSave} disabled={loading} icon={loading ? <LoadingOutlined /> : ''}>
            保存
        </Button>
    )
}

/**
 * 发布按钮组件逻辑
 * 发布的本质也是组件更新
 * */
const PublishButton: FC = () => {
    const { id } = useParams() // 问卷id
    const { componentsList = [] } = useGetComponentInfo() // 问卷列表
    const pageInfo = useGetPageInfo() // 问卷页面信息
    const nav = useNavigate()

    const { loading, run: handlePublish } = useRequest(
        async () => {
            if (!id) return
            await updateQuestionServices(id, {
                ...pageInfo,
                componentsList,
                isPublished: true,
            })
        },
        {
            manual: true,
            onSuccess() {
                message.success('发布成功')
                nav(`/question/stat/${id}`)
            },
        }
    )
    return (
        <Button type="primary" onClick={handlePublish} disabled={loading}>
            发布
        </Button>
    )
}
// 编辑器头部
const EditHeader: FC = () => {
    const nav = useNavigate()
    return (
        <div className={styles['header-wrapper']}>
            <div className={styles.header}>
                <div className={styles.left}>
                    <Space>
                        <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
                            返回
                        </Button>
                        {/* 问卷标题 */}
                        <TitleElem />
                    </Space>
                </div>
                <div className={styles.main}>
                    <EditToolbar />
                </div>
                <div className={styles.right}>
                    <Space>
                        <SaveEButtonElem />
                        <PublishButton />
                    </Space>
                </div>
            </div>
        </div>
    )
}
export default EditHeader
